"""
本脚本用于自动打包版本:
    1.双击运行本脚本，自动打包版本所需文件到 output
"""


import os
import shutil
import zipfile


# 0.独立版本号；1.总版本号 
TOTAL_VERSION = 0


OUTPUT_PATH = "output"
VER_BASE_NAME = "2.1.2_0000"
OTA_BIN = "tlsr_ota_pid_"
TOTAL_BIN = "app.bin"
READ_ME = "readme.txt"
SRC_FILE = (OTA_BIN, TOTAL_BIN, READ_ME)
DEL_FILE = (OTA_BIN, TOTAL_BIN)

src_file_path = r"..\xiaomi\mijia_ble_mesh\gwin\gwin_product_info.h"    # 源码文件路径
product_model_begin_symbol_str = "GWIN_PRODUCT_MODEL_BEGIN"             # 全产品一键编译脚本标识符 model宏
product_model_end_symbol_str = "GWIN_PRODUCT_MODEL_END"                 # 全产品一键编译脚本标识符 model宏
product_version_symbol_str = "GWIN_PRODUCT_APP_DEVELOPER_VERSION"       # 标识符 版本号
product_type_symbol_str = "GWIN_PRODUCT_TYPE "                          # 标识符 产品宏定义
product_model_symbol_str = "GWIN_PRODUCT_MODEL"                         # 标识符 model
product_fw_name_symbol_str = "GWIN_FW_NAME_PREFIX"                      # 标识符 固件名
product_project_index_symbol_str = "GWIN_PROJECT_INDEX"                 # 标识符 项目编号



# 清空文件夹
def system_makedir(path):
    if os.path.exists(path):
        shutil.rmtree(path)
    os.makedirs(path)


# 模糊搜索
def system_fuzzy_search(path, file, is_dir):
    total_file_name = ""
    file_list = os.listdir(path)
    for i in file_list:
        if i.find(file) >= 0:
            if (not is_dir or os.path.isdir(path + os.sep + i)):
                total_file_name = i
                break
    return total_file_name


# 检查文件是否都存在，返回完整路径
def system_check_file_list_exist(path, src_list):
    total_path_list = []
    for i in range(len(src_list)):
        file_total_name = system_fuzzy_search(path, src_list[i], 0)
        if file_total_name == "":
            print("error : no %s bin." % src_list[i])
            os.system("pause")
            exit()
        else:
            total_path_list.append(path + os.sep + file_total_name)
    return total_path_list


# 打包目录为zip文件
def system_make_zip(source_dir, output_filename):
    zipf = zipfile.ZipFile(output_filename, 'w')
    pre_len = len(os.path.dirname(source_dir))
    for parent, dirnames, filenames in os.walk(source_dir):
        for filename in filenames:
            print(filename)
            pathfile = os.path.join(parent, filename)
            arcname = pathfile[pre_len:].strip(os.path.sep)  # 相对路径
            zipf.write(pathfile, arcname)
        print()
    zipf.close()


# 每行字符串分隔目标字符串
def line_find_str(line, start_str, filter_symbol_map, end_symbol):
    ret = ""
    start = line.find(start_str)
    if (start > 0):
        start = start + len(start_str)
        while (1):
            filter = 0
            for i in range(len(filter_symbol_map)):
                if (line[start] == filter_symbol_map[i]):
                    filter = 1;
                    break;
            if (filter):
                start = start + 1
            else:
                break;
        end = line[start:].find(end_symbol)
        if (end > 0):
            ret = line[start : start + end]
    return ret



# main函数
if __name__ == '__main__':
    if not os.path.exists(OUTPUT_PATH):
        os.makedirs(OUTPUT_PATH)

    # 检查文件是否都存在
    total_path_list = system_check_file_list_exist(".", SRC_FILE)

    # 1.查找model、固件名、项目编号
    print("1.查找model、固件名、项目编号")
    product_version = ""
    product_model = ""
    product_fw_name = ""
    product_index = ""
    with open(src_file_path, "r", encoding = 'utf-8') as src_file_fd:
        product_type_str = ""
        find_product_type = 0
        find_begin_symbol = 0
        for line in src_file_fd:
            if (TOTAL_VERSION == 1):
                # 确认版本号
                if (product_version == ""):
                    product_version = line_find_str(line, product_version_symbol_str, (' ', '\t', '\"'), '\n')
            # 确认当前产品
            if (product_type_str == ""):
                product_type_str = line_find_str(line, product_type_symbol_str, (' ', '\t', '\"'), '\n')
            else:
                if (find_begin_symbol == 0):
                    if (line.find(product_model_begin_symbol_str) > 0):
                        find_begin_symbol = 1
                else:
                    if (line.find(product_model_end_symbol_str) > 0):
                        break
                    else:
                        if (find_product_type == 0):
                            if (line.find(product_type_str) > 0):
                                find_product_type = 1
                        else:
                            if (TOTAL_VERSION == 0):
                                # 确认版本号
                                if (product_version == ""):
                                    product_version = line_find_str(line, product_version_symbol_str, (' ', '\t', '\"'), '\n')
                            # 查找model
                            if (product_model == ""):
                                product_model = line_find_str(line, product_model_symbol_str, (' ', '\t', '\"'), '\"')
                            # 查找固件名
                            if (product_fw_name == ""):
                                product_fw_name = line_find_str(line, product_fw_name_symbol_str, (' ', '\t', '\"'), '\n')
                            # 查找固件名
                            if (product_index == ""):
                                product_index = line_find_str(line, product_project_index_symbol_str, (' ', '\t', '\"'), '\n')
                                if (product_index != ""):
                                    product_index = product_index[2:]
                            # 结束
                            if (line.find(product_type_symbol_str) > 0):
                                break
    print(total_path_list)
    print(product_version)
    print(product_model)
    print(product_fw_name)
    print(product_index)
    print("")

    if (len(total_path_list) == 0 or product_version == "" or product_model == "" or product_fw_name == "" or product_index == ""):
        os.system("pause")
        exit()

	# 2.创建文件夹
    print("2.创建文件夹")
    version_folder_name = VER_BASE_NAME[:-len(product_version)] + product_version
    version_folder_path = os.path.join(OUTPUT_PATH, version_folder_name)
    version_folder_path_new = os.path.join(OUTPUT_PATH, product_fw_name + "-" + version_folder_name)
    system_makedir(version_folder_path)

    # 3.复制文件
    print("3.复制文件")
    for i in range(len(total_path_list)):
        shutil.copy(total_path_list[i], version_folder_path)

    # 4.压缩
    print("4.压缩")
    system_make_zip(version_folder_path, version_folder_path + ".zip")
    # 5.改名
    print("5.改名")
    if os.path.exists(version_folder_path_new + ".zip"):
        os.remove(version_folder_path_new + ".zip")
    os.rename(version_folder_path + ".zip", version_folder_path_new + ".zip")
    # 6.移动到项目路径
    project_path = system_fuzzy_search(OUTPUT_PATH, product_index, 1)
    if (project_path != ""):
        print("6.移动到项目路径")
        project_file = os.path.join(OUTPUT_PATH, project_path, os.path.basename(version_folder_path_new) + ".zip")
        if os.path.exists(project_file):
            os.remove(project_file)
        shutil.move(version_folder_path_new + ".zip", project_file)

    # 7.删除文件
    print("7.删除文件")
    shutil.rmtree(version_folder_path)
    total_path_list = system_check_file_list_exist(".", DEL_FILE)
    for i in range(len(total_path_list)):
        os.system("del " + total_path_list[i])



